/**
 * Tiem: 2023-1-9
 * FileName: Taxi Missions(打车任务)
 * Editor: Haidong
 */

import React, { Component } from 'react';
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import store from "@/store/store";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import { Table, Space, Radio, Tooltip } from "antd";
import { apiGetMissionsPage, apiGetMissionsExport, apiPostChauffeurPage } from "@/request/petTaxi";
import { exportSheetTable } from '@/utils/exportTable'
import { getDateTime3 } from '@/utils/getDate';
import moment from 'moment';
import _ from 'lodash';
import "./style/index.less";

class TaxiMissions extends Component {
    constructor(props) {
        super();
        this.queryFormRef = React.createRef()
        this.heightRef = React.createRef()
        this.searchRef = React.createRef()
        this.pageHeight = React.createRef()
        this.refs = React.createRef()
        this.tableRefs = React.createRef()
        this.state = {
            form_show: true,
            down_loading: false,
            columns: [
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key: "createTime",
                    onCell: () => {
                        return {
                            style: {
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip>
                    }
                },
                {
                    title: "任务ID",
                    dataIndex: "taskId",
                    key: "taskId",
                },
                // {
                //     title: "任务类型",
                //     dataIndex: "type",
                //     key: "type",
                //     render:()=>{
                //         return "宠物打车"
                //     } 
                // },
                {
                    title: "任务单号",
                    dataIndex: "distributionCode",
                    key: "distributionCode",
                },
                {
                    title: "任务内容",
                    dataIndex: "petNameVariety",
                    key: "petNameVariety",
                    ellipsis: {
                        showTitle: false,
                    },
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 140,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip>
                    }
                },
                {
                    title: "地址",
                    dataIndex: "endAddress",
                    key: "endAddress",
                    width: 150,
                    ellipsis: true,
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 140,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text, render) => {
                        return <Tooltip placement="topLeft" title={render.endAddress + (render.endPhone ? "/" + render.endPhone : "")}>
                            {render.endAddress + (render.endPhone ? "/" + render.endPhone : "")}
                        </Tooltip>
                    }
                },
                {
                    title: "客户",
                    dataIndex: "memberName",
                    key: "memberName",
                    ellipsis: true,
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 140,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text, render) => {
                        return <Tooltip placement="topLeft" title={render.memberName + '/' + render.memberPhone ? (render.memberPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2") : ""}>
                            {render.memberName + '/' + render.memberPhone ? (render.memberPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2") : ""}
                        </Tooltip>
                    }
                },
                {
                    title: "司机",
                    dataIndex: "driverName",
                    key: "driverName",
                    ellipsis: true,
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 140,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text, render) => {
                        if (text) {
                            return <Tooltip placement="topLeft" title={render.driverName + '/' + (render.driverPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2")}>
                                {render.driverName + '/' + (render.driverPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2")}
                            </Tooltip>
                        } else {
                            return "/"
                        }
                    }
                },
                {
                    title: "任务状态",
                    dataIndex: "taskStatus",
                    key: "taskStatus",
                    render: (text) => {
                        let taskStatus = ''
                        switch (text) {
                            case 1:
                                taskStatus = '待接单'
                                break;
                            case 2:
                                taskStatus = '接乘中'
                                break;
                            case 3:
                                taskStatus = '送达中'
                                break;
                            case 4:
                                taskStatus = '已完成'
                                break;
                            case 5:
                                taskStatus = '客户取消'
                                break;
                            case 6:
                                taskStatus = '司机取消'
                                break;
                            case 7:
                                taskStatus = '待出发'
                                break;
                            default:
                                break;
                        }
                        return taskStatus
                    }
                },
                // {
                //     title: "关联订单号",
                //     dataIndex: "orderId",
                //     key: "index", 
                // },
                {
                    title: "备注",
                    dataIndex: "remark",
                    key: "index",
                    ellipsis: true,
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 140,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip>
                    }
                },
                {
                    title: "操作",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['Taxi:missions:view']} onClick={() => this.view(render)}>查看详情</TheButton>
                        </div>
                    }
                },
            ],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: "",
            newColumns: [],
            dataSource: [],
            queryForm: {},
            taskStatus: "",
            searchOption: [
                { field: 'taskId', label: '任务ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'code', label: '任务单号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'status', label: '任务类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '宠物打车', value: '0', }, { label: '酒店打车', value: '1' }], defaultValue: '' },
                { field: 'petNameVariety', label: '任务内容', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'time', label: '创建时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
                { field: 'driverId', label: '所属司机', placeholder: '请选择', required: false, rules: [], type: 'Select', txt: 'nickname', value: 'driverId', options: [], defaultValue: '' },
                // { field: 'status', label: '任务状态', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '未完成', value: '0', }, { label: '已完成', value: '1' }], defaultValue: '' },
            ],
            tableHeight: '',
            Height: '',
        }
    }
    //Initialization
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let cacheData = store.getState().dataSource
        let { pageNo, pageSize, queryForm, taskStatus ,pathName} = searchParams
        let Height = this.pageHeight.current.clientHeight - this.searchRef.current.offsetHeight - 50
        let tableHeight = Height - 150
        if (queryForm && queryForm.beginTime) {
            queryForm.time = [moment(queryForm.beginTime, 'YYYY/MM/DD'), moment(queryForm.endTime, 'YYYY/MM/DD')]
        }
        this.setState({
            tableHeight,
            Height
        })
        if (cacheData) {
            this.setState({
                dataSource: cacheData.dataSource,
                queryForm,
                taskStatus,
                pageData: {
                    pageNo, pageSize
                },
                total: cacheData.total
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                store.dispatch({
                    type: 'ClearDataSource',
                    data: ""
                })
            })
        } else {
            if (searchParams && pageNo&&pathName=='missions') {
                this.setState({
                    queryForm,
                    taskStatus,
                    pageData: {
                        pageNo, pageSize
                    }
                }, () => {
                    this.queryFormRef.onSetDefault({
                        ...queryForm
                    })
                    this.getData()
                })
            } else {
                this.getData()
            }
        }
        this.getChauffeurList()
        this.tableScrollView()
    }
    //CTRL
    //表格title
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })

    }
    //获取数据
    getData = async (values) => {
        const { taskStatus } = this.state
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.beginTime = getDateTime3(values.time[0]) + ' 00:00:00'
            values.endTime = getDateTime3(values.time[1]) + ' 23:59:59'
            delete (values.time)
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values, }
        }, async () => {
            const params = {
                pageNo, pageSize, taskStatus, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName:"missions",
                    ...params
                }
            })
            let res = await apiGetMissionsPage({
                pageNo, pageSize, taskStatus, ...this.state.queryForm
            })
            if (res.code === 0 && res.data) {
                console.log(res);
                this.setState({ dataSource: res.data, total: res.totalCount })
            }
        })
    }
    //获取司机列表
    getChauffeurList = async () => {
        await apiPostChauffeurPage({ pageNo: 1, pageSize: '-1' })
            .then(res => {
                if (res.code === 0 && res.data) {
                    this.state.searchOption[3].options = res.data
                    this.setState({
                        searchOption: this.state.searchOption
                    })
                }
            })
    }
    //分页查询
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    }
    //重置
    onReset() {
        this.setState({
            taskStatus: "",
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    //搜索
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }
    //导出
    export = async () => {
        let params = this.state.queryForm
        this.setState({ down_loading: true })
        await apiGetMissionsExport({ ...params })
            .then(res => {
                if (res.code === 0) {
                    let tH_data = [
                        {
                            title: '宠物打车任务列表',
                            prop: '',
                            children: [
                                { prop: 'createTime', title: '创建时间' },
                                { prop: 'taskId', title: '任务ID' },
                                // { prop: 'type', title: '任务类型' },
                                { prop: 'distributionCode', title: '任务单号' },
                                { prop: 'petNameVariety', title: '任务内容' },
                                { prop: 'endAddress', title: '店铺' },
                                { prop: 'memberName', title: '客户' },
                                { prop: 'driverName', title: '司机' },
                                { prop: 'taskStatus', title: '任务状态' },
                                { prop: 'remark', title: '备注' },
                            ]
                        }
                    ]
                    let tB_data = res.data.map(item => {
                        let taskStatus = ''
                        switch (item.taskStatus) {
                            case 1:
                                taskStatus = '待接单'
                                break;
                            case 2:
                                taskStatus = '接乘中'
                                break;
                            case 3:
                                taskStatus = '送达中'
                                break;
                            case 4:
                                taskStatus = '已完成'
                                break;
                            case 5:
                                taskStatus = '客户取消'
                                break;
                            case 6:
                                taskStatus = '司机取消'
                                break;
                            case 7:
                                taskStatus = '待出发'
                                break;
                            default:
                                taskStatus = '/'
                                break;
                        }
                        return {
                            createTime: item.createTime,
                            taskId: item.taskId,
                            // type: '宠物打车',
                            distributionCode: item.distributionCode,
                            petNameVariety: item.petNameVariety,
                            endAddress: item.endAddress ? item.endAddress + "/" + item.endPhone : "",
                            memberName: item.memberName + '/' + (item.memberPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2"),
                            driverName: item.driverName ? item.driverName + '/' + (item.driverPhone).replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2") : '/',
                            taskStatus: taskStatus,
                            remark: item.remark ? item.remark : "/",
                        }
                    })
                    this.setState({ down_loading: false })
                    exportSheetTable({
                        fileName: '打车任务列表', tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false,
                    })
                }
            })
            .catch(err => {
                React.$message({
                    type: 'warning',
                    content: '导出操作失败,请重试'
                })
                this.setState({ down_loading: false })
            })

    }
    //状态按钮切换
    handleStatusChange = (e) => {
        let { queryForm, taskStatus } = this.state
        taskStatus = e.target.value
        this.setState({
            pageData:{
                pageNo:1,
                pageSize:10
            },
            taskStatus,
        }, () => {
            this.queryFormRef.onSetDefault({
                ...queryForm
            })
            this.getData()
        })
    }

    //查看详情
    view = (render) => {
        this.tableScrollView()
        const { dataSource, total } = this.state
        store.dispatch({
            type: 'SaveDataSource',
            data: {
                dataSource,
                total
            }
        })
        this.props.history.push(`/missions/detail/${render.taskId}`);
    }
    tableScrollView() {
        const tableScrollTop = store.getState().tableScrollTop
        const v = document.getElementsByClassName("ant-table-body")[0]
        if (tableScrollTop) {
            setTimeout(() => {
                v.scrollTop = tableScrollTop
            }, 500)
            store.dispatch({
                type: 'Clear_tableScrollTop',
                data: 0
            })
        } else {
            store.dispatch({
                type: 'Set_tableScrollTop',
                data: v.scrollTop
            })
        }

    }
    //View
    render() {
        let { columns, form_show, searchOption, newColumns, dataSource, pageData:{pageNo,pageSize}, total, taskStatus } = this.state
        return (
            <div className='missionsPage' ref={this.pageHeight}>
                <div ref={this.searchRef}>
                    <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                        onReset={() => this.onReset()}
                        onGetValues={(values) => { this.onFormSearch(values) }} >
                    </TheQueryForm>
                    <TheTableExtend
                        columns={columns}
                        onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                        onTableRefresh={() => this.getData()}
                        onColumnsFilter={(value) => this.onColumnsFilter(value)}
                    >
                        <TheButton haspermi={['Taxi:missions:export']} size="middle" onClick={() => this.export()} type="primary">导出</TheButton>

                    </TheTableExtend>
                    <Space direction="vertical" size="middle" style={{ marginBottom: '10px' }}>
                        <Radio.Group value={taskStatus} onChange={this.handleStatusChange}>
                            <Radio.Button value="">全部</Radio.Button>
                            <Radio.Button value="1">待接单</Radio.Button>
                            <Radio.Button value="7">待出发</Radio.Button>
                            <Radio.Button value="2">接乘中</Radio.Button>
                            <Radio.Button value="3">送达中</Radio.Button>
                            <Radio.Button value="4">已完成</Radio.Button>
                            <Radio.Button value="5">已取消</Radio.Button>
                        </Radio.Group>
                    </Space>
                </div>
                <div className='p-layout-content-pagination'>
                    <Table columns={newColumns} dataSource={dataSource} pagination={false} bordered={1}
                        scroll={{ x: 'max-content', y: '55vh' }} ref={this.tableRefs} id='tabel'
                    ></Table>
                    <ThePagination
                        pageNo={pageNo}
                        pageSize={pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </div>

            </div>
        )
    }
}

export default TaxiMissions